package com.shxc.smarttrade.index.fragment;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.shxc.smarttrade.R;
import com.shxc.smarttrade.base.BaseFragment;
import com.shxc.smarttrade.currency.model.CurrencyModel;
import com.shxc.smarttrade.dialog.SubmitDialog;
import com.shxc.smarttrade.index.activity.IndexMessageDetailsActivity;
import com.shxc.smarttrade.index.activity.MessageCenterActivity;
import com.shxc.smarttrade.index.adapter.MessageAdapter;
import com.shxc.smarttrade.index.model.MessageModel;
import com.shxc.smarttrade.info.Contents;
import com.shxc.smarttrade.utils.analysis.JsonAnalysisModel;
import com.shxc.smarttrade.utils.analysis.JsonAnalysisUtils;
import com.shxc.smarttrade.utils.MyOkHttpUtils;
import com.shxc.smarttrade.utils.ToastUtils;

import org.xchris.view.annotation.ContentView;
import org.xchris.view.annotation.Event;
import org.xchris.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 首页 - 消息
 */
@ContentView(R.layout.fragment_index_message)
public class IndexMessageFragment extends BaseFragment {

    @ViewInject(R.id.load_view)
    LinearLayout load_view;
    @ViewInject(R.id.loading_view)
    LinearLayout loading_view;
    @ViewInject(R.id.null_view)
    RelativeLayout null_view;
    @ViewInject(R.id.loadingfaild_view)
    LinearLayout loadingfaild_view;
    @ViewInject(R.id.swiperefreshlayout)
    SwipeRefreshLayout swiperefreshlayout;
    @ViewInject(R.id.recyclerview)
    RecyclerView recyclerview;
    @ViewInject(R.id.oprate_linearlayout)
    LinearLayout oprate_linearlayout;
    @ViewInject(R.id.all_textview)
    TextView all_textview;
    @ViewInject(R.id.read_textview)
    TextView read_textview;
    @ViewInject(R.id.foot_view)
    View foot_view;

    private List<MessageModel.DataBean> list;
    private MessageAdapter adapter;

    private int page = 1;
    private int size = 10;
    private boolean isRefresh = true;

    private boolean isOprate = false;

    private String msgId = "";//信息ID ","隔开

    private MessageCenterActivity messageCenterActivity;
    private List<MessageModel.DataBean> chooseList;
    private boolean isRead = false;
    private boolean isAll = false;

    private SubmitDialog submitDialog;

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        loading_view.setVisibility(View.VISIBLE);
        list = new ArrayList<>();
        adapter = new MessageAdapter(mContext, list, handler);
        recyclerview.setAdapter(adapter);
        recyclerview.setLayoutManager(new LinearLayoutManager(mContext));

        messageCenterActivity = (MessageCenterActivity) getActivity();
        chooseList = new ArrayList<>();
        //初始化dialog
        submitDialog = new SubmitDialog(getActivity(),
                getActivity().getResources().getIdentifier("MyDialog", "style", getActivity().getPackageName()));

        //设置滑动监听事件
        swiperefreshlayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 1;
                isRefresh = true;
                initData();
            }
        });
        recyclerview.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (isRefresh) {
                    page ++;
                    foot_view.setVisibility(View.VISIBLE);
                    initData();
                }else{
                    ToastUtils.showToast("暂无更多数据");
                }
            }
        });

        initData();

    }

    @Event({R.id.all_textview, R.id.read_textview, R.id.delete_textview})
    private void onClick(View view) {

        switch (view.getId()) {
            case R.id.all_textview:
                //全选
                adapter.checkAll(!isAll);
                chooseList = adapter.getChooseList();
                isAll = !isAll;
                listenAll();
                checkRead();
                break;
            case R.id.read_textview:
                //已读
                msgId = "";
                if (!isRead) {
                    for (int i = 0; i < chooseList.size(); i++) {
                        if (chooseList.get(i).getStatus() == 0) {
                            if (msgId.equals("")) {
                                msgId = chooseList.get(i).getId() + "";
                            } else {
                                msgId = msgId + "," + chooseList.get(i).getId();
                            }
                        }
                    }
                    msgRead();
                }
                break;
            case R.id.delete_textview:
                //删除
                msgId = "";
                for (int i = 0; i < chooseList.size(); i++) {
                    if (i==0) {
                        msgId = chooseList.get(0).getId()+"";
                    }else{
                        msgId = msgId + ","+chooseList.get(i).getId();
                    }
                }
                submitDialog.showDialog("您所选中的消息将被删除，确定删除吗？");
                submitDialog.getCancel_textview().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        submitDialog.dismiss();
                    }
                });
                submitDialog.getSubmit_textview().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        msgDel();
                        submitDialog.dismiss();
                    }
                });
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        page = 1;
        initData();
    }

    Handler handler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    //判断是否显示底部操作栏
                    if (isOprate) {
                        oprate_linearlayout.setVisibility(View.VISIBLE);
                        chooseList = adapter.getChooseList();
                        checkRead();
                    } else {
                        oprate_linearlayout.setVisibility(View.GONE);
                        chooseList.clear();
                    }
                    break;
                case 1:
                    //點擊
                    MessageModel.DataBean model = (MessageModel.DataBean) msg.obj;
                    if (!isOprate) {
                        //未编辑，消息已读，跳转到消息详情
                        msgId = model.getId() + "";
                        if (model.getStatus()==0) {
                            msgRead();
                        }
                        bundle.putString("title", model.getMsgTitle());
                        bundle.putLong("time", model.getCreatedAt());
                        bundle.putString("content", model.getMsgInfo());
                        JumpTo(IndexMessageDetailsActivity.class, bundle);
                    } else {
                        chooseList = adapter.getChooseList();
                        if (chooseList.size() == list.size()) {
                            isAll = true;
                        } else {
                            isAll = false;
                        }
                        listenAll();
                        checkRead();
                    }
                    break;
                case 2:
                    //长按
                    if (!isOprate) {
                        isOprate = true;
                        messageCenterActivity.setOprate(true);
                        chooseList = adapter.getChooseList();
                        if (chooseList.size() == list.size()) {
                            isAll = true;
                        } else {
                            isAll = false;
                        }
                        listenAll();
                        checkRead();
                        oprate_linearlayout.setVisibility(View.VISIBLE);
                    }
                    break;
            }
            super.dispatchMessage(msg);
        }
    };

    private void listenAll() {
        if (isAll) {
            all_textview.setText("取消全选");
        } else {
            all_textview.setText("全选");
        }
    }

    //判断已读按钮
    private void checkRead() {
        isRead = true;//默认全部已读
        for (int i = 0; i < chooseList.size(); i++) {
            if (chooseList.get(i).getStatus() == 0) {
                isRead = false;
                break;
            }
        }
        if (isRead) {
            read_textview.setBackgroundColor(resources.getColor(R.color.msg_read_gray));
        } else {
            read_textview.setBackgroundColor(resources.getColor(R.color.quotation_gray));
        }
    }

    public void setOprate(boolean oprate) {
        this.isOprate = oprate;
        handler.sendEmptyMessage(0);
        adapter.setOprate(oprate);
    }

    /**
     * 消息列表
     */
    private void initData() {
        Map<String, Object> map = new HashMap<>();
        map.put("page", page);
        map.put("pageSize", size);
        map.put("userId", spImp.getUserId());

        MyOkHttpUtils.getServiceDatas(map, Contents.MSG_LIST, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void success(String response, int d) {
                if (response != null) {
                    JsonAnalysisModel jam = JsonAnalysisUtils.jsonAnalysis(response, MessageModel.class);
                    if (jam.isSuccess()) {
                        MessageModel model = (MessageModel) jam.getData();
                        if (page == 1) {
                            list.clear();
                            list = model.getData();
                        } else {
                            list.addAll(model.getData());
                        }
                        int ii = 0;
                        for (int i = 0; i < list.size(); i++) {
                            if (list.get(i).getStatus() == 0) {
                                ii++;
                            } else {
                                break;
                            }
                        }
                        adapter.upDate(list);
                        load_view.setVisibility(View.GONE);
                        messageCenterActivity.setRightText(View.VISIBLE);
                        listenAll();
                        checkRead();
                        if (model.getData().size() < size) {
                            isRefresh = false;
                        }
                    } else {
                        if (list.size() == 0) {
                            messageCenterActivity.setRightText(View.GONE);
                            null_view.setVisibility(View.VISIBLE);
                            load_view.setVisibility(View.GONE);
                        } else {
                            ToastUtils.showToast("暂无更多数据");
                            null_view.setVisibility(View.GONE);
                            load_view.setVisibility(View.GONE);
                        }
                    }
                }
                foot_view.setVisibility(View.GONE);
                swiperefreshlayout.setRefreshing(false);
                loadingDialog.dismiss();
            }

            @Override
            public void faild(Call call, Exception e, int id) {
                loadingDialog.dismiss();
                swiperefreshlayout.setRefreshing(false);
                load_view.setVisibility(View.VISIBLE);
                loadingfaild_view.setVisibility(View.VISIBLE);
                foot_view.setVisibility(View.GONE);
            }
        });
    }

    /**
     * 消息已读
     */
    private void msgRead() {
        if (isOprate) {
            loadingDialog.show();
        }
        Map<String, Object> map = new HashMap<>();
        map.put("msgId", msgId + "");

        MyOkHttpUtils.getServiceDatas(map, Contents.MSG_READ, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void success(String response, int d) {
                if (response != null) {
                    JsonAnalysisModel jam = JsonAnalysisUtils.jsonAnalysis(response, CurrencyModel.class);
                    if (jam.isSuccess()) {
                        CurrencyModel model = (CurrencyModel) jam.getData();
                        //已读成功
                        readList();
                        messageCenterActivity.msghavemsg();
                    } else {
                        ToastUtils.showToast("操作出错，请重试");
                    }
                }
                loadingDialog.dismiss();
            }

            @Override
            public void faild(Call call, Exception e, int id) {
                loadingDialog.dismiss();
            }
        });
    }

    /**
     * 消息删除
     */
    private void msgDel() {

        loadingDialog.show();
        Map<String, Object> map = new HashMap<>();
        map.put("msgId", msgId + "");
        map.put("userId", spImp.getUserId() + "");

        MyOkHttpUtils.getServiceDatas(map, Contents.MSG_DELMSG, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void success(String response, int d) {
                if (response != null) {
                    JsonAnalysisModel jam = JsonAnalysisUtils.jsonAnalysis(response, CurrencyModel.class);
                    if (jam.isSuccess()) {
                        //删除成功
                        delList();
                    } else {
                        ToastUtils.showToast("操作出错，请重试");
                    }
                }
                loadingDialog.dismiss();
            }

            @Override
            public void faild(Call call, Exception e, int id) {
                loadingDialog.dismiss();
            }
        });
    }

    private void delList() {
            String[] ids = msgId.split(",");
            for (int i = 0; i < ids.length; i++) {
                for (int j = 0; j < list.size(); j++) {
                    if (list.get(j).getId() == Long.parseLong(ids[i])) {
                        list.remove(j);
                        break;
                    }
                }
            }
            adapter.upDate(list);
    }
    private void readList() {
        String[] ids = msgId.split(",");
        for (int i = 0; i < ids.length; i++) {
            long id = Long.parseLong(ids[i]);
            for (int j = 0; j < list.size(); j++) {
                if (list.get(j).getId() == id) {
                    list.get(j).setStatus(1);
                    break;
                }
            }
        }
        adapter.upDate(list);
    }
}
